import requests
import redis
import base64
# API Key
# geI0bg4tSbtSrr4zOk3Gjxij
#
# Secret Key
# 4GG7kpoe4WkHWjWtHkatbHZrjc9rioN1
# 封装 百度类
class Baidu:
    def __init__(self):
        self.apikey = 'geI0bg4tSbtSrr4zOk3Gjxij'
        self.apisecret = '4GG7kpoe4WkHWjWtHkatbHZrjc9rioN1'

        self.redis = redis.Redis(decode_responses=True)

    # 文字识别
    def ocr(self,filename):

        # 定义请求地址
        request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic'
        # 读取图片
        f = open(filename,'rb')
        # base64编码
        img = base64.b64encode(f.read())
        # 定义请求参数
        params = {"image": img}
        access_token = self.redis.get("baidutoken")
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        # 发起请求
        response = requests.post(request_url, data=params, headers=headers)

        if response:
            print(response.json())
            # 获取识别结果
            try:
                num = ""
                for x in response.json()["words_result"]:
                    num += x["words"]
            except:
                num = None

            return num

    # 获取token
    def get_token(self):
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (
        self.apikey, self.apisecret)
        response = requests.get(host)
        if response:
            print(response.json())
            try:
                self.redis.set('baidutoken',response.json()['access_token'])
            except Exception as e:
                print('请求报错，无法获取token')

if __name__ == '__main__':
    # baidu = Baidu()
    # baidu.get_token()
    # print(baidu.ocr())

    times = 0 # 定义计数器
    success = False  # 成功标识

    while times < 3 and not success:

        print('尝试第%s次'%(times+1))

        if(times == 0):
            success = True
        times += 1
